package com.javasm.filter;

import com.alibaba.fastjson.JSON;
import com.javasm.entity.ReturnCodeEnum;
import com.javasm.entity.ReturnResult;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @version 0.1
 * @className: MyFilter2
 * @description:
 * @author: gfs
 * @date: 2025/6/25 11:14
 * @since: jdk17
 */
//@WebFilter("/*")
public class MyFilter3 implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        //当次请求路径
        String currentPath = req.getServletPath();
        //当前用户的url列表全集
        List<String> loginUserUrl =(List<String>) session.getAttribute("loginUserUrl");


        System.out.println("当次请求路径:"+currentPath);
        System.out.println("当前用户的url列表:"+loginUserUrl);
        //白名单
        //1.默认每个用户都需要拥有 不需要单独配置的请求路径
        //2.静态资源(用户头像)
        if("/myupload".equals(currentPath)||"/login".equals(currentPath)||"/logout".equals(currentPath)||currentPath.endsWith(".jpg")||currentPath.endsWith(".png")||currentPath.endsWith(".gif")){
            chain.doFilter(req, resp);
        }else{
            //当次路径是否在这个集合中
            if(loginUserUrl.contains(currentPath)) {
                chain.doFilter(req, resp);
            }else{
                ReturnResult returnResult = new ReturnResult();

                returnResult.setCode(ReturnCodeEnum.NO_PORMISSION.getCode());
                returnResult.setMsg(ReturnCodeEnum.NO_PORMISSION.getMsg());

                //用输出流输出JSON字符串
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                writer.print(JSON.toJSONString(returnResult));
                writer.close();
            }
        }







    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }


}
